package cn.wikiflyer.beikang.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import cn.wk.libs4a.WKApplication;
import cn.wk.libs4a.bean.PhotoPathBean;
import cn.wk.libs4a.utils.L;

/**
 *	上传文件 工具类
 */
public class BKUploadUtil {

	public UploadCallBack callback;
	ArrayList<NameValuePair> localParams;

	/**
	 * 上传结果回掉类
	 */
	public interface UploadCallBack {
		public void success(String result);

		public void failed();
	}

	/**
	 * 上传图片 （线程内调用）
	 * @param filePath
	 * @param user_id			用户对应的id
	 * @param callback
	 * @param handler
	 */
	public void avatarUpload(final URL url, final String filePath,
			String user_id, String param, UploadCallBack callback, final Handler handler) {
		this.callback = callback;
		localParams = new ArrayList<NameValuePair>();
		localParams.add(new BasicNameValuePair(param, user_id));
		new Thread() {
			@Override
			public void run() {
				avatarUpload(url, filePath, localParams, handler);
			}
		}.start();
	}
	/**上传图片  到指定Url
	 * @param url
	 * @param filePath
	 * @param callback
	 * @param handler
	 */
	public void avatorUploadUrl(final URL url,final String filePath,UploadCallBack callback,final Handler handler){
		this.callback = callback;
		new Thread() {
			@Override
			public void run() {
				avatarUpload(url, filePath, localParams, handler);
			}
		}.start();
	}

	/**
	 * 上传图片
	 */
	private void avatarUpload(URL url, String filePath,
			ArrayList<NameValuePair> params, Handler handler) {
		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
//		String MULTIPART_FROM_DATA = "multipart/form-data";
		String MULTIPART_FROM_DATA = "text/xml";
//		String MULTIPART_FROM_DATA = "application/x-jpg";
		String CHARSET = "UTF-8";
		try {
			L.wj("url : " + url.toString());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(5 * 1000); // 缓存的最长时间
			conn.setDoInput(true);// 允许输入
			conn.setDoOutput(true);// 允许输出
			conn.setUseCaches(false); // 不允许使用缓存
			System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
			conn.setRequestMethod("POST");
			conn.setRequestProperty("connection", "keep-alive");
//			conn.setRequestProperty("Charsert", CHARSET);
//			conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
//					+ ";boundary=" + BOUNDARY);
			conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA);
			// 首先组拼文本类型的参数
			StringBuilder sb = new StringBuilder();
			DataOutputStream outStream = new DataOutputStream(
					conn.getOutputStream());
			outStream.write(sb.toString().getBytes());
			InputStream in = null;
			File file = new File(filePath);
//			File file = new File("/storage/emulated/0/crop/test.txt");
			L.wj("file : " + file.toString());
			// 发送文件数据
			StringBuilder sb1 = new StringBuilder();
			sb1.append(PREFIX);
			sb1.append(BOUNDARY);
			sb1.append(LINEND);
//			sb1.append("Content-Disposition: form-data; name=\"img\"; filename=\""+ file.getName() + "\"" + LINEND);
//			sb1.append("Content-Type: application/octet-stream; charset="+ CHARSET + LINEND);
//			sb1.append(LINEND);
//			outStream.write(sb1.toString().getBytes());

			InputStream is = new FileInputStream(file);
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = is.read(bytes)) != -1) {
//				L.wj("len:"+new String(bytes));
				outStream.write(bytes, 0, len);
			}
			is.close();
			outStream.write(LINEND.getBytes());
			// 请求结束标志
			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
			outStream.write(end_data);
			outStream.flush();
			outStream.close();
			// 得到响应码
			int res = conn.getResponseCode();
			L.wj("ResponseCode :"+res);
			if (res == 200) {
				in = conn.getInputStream();
				// L.wj("result : "+dealResponseResult(in));
				Message message = handler.obtainMessage(1);
				message.obj = dealResponseResult(in);
				handler.sendMessage(message);
			} else {
				handler.sendEmptyMessage(0);
				conn.disconnect();
				throw new IOException("服务器返回错误：" + res);
			}
		} catch (Exception e) {
			e.printStackTrace();
			handler.sendEmptyMessage(0);
		}
	}

	/**
	 * 解析返回的json结果
	 */
	public PhotoPathBean parseJson(String jsonStr, String photo_path) throws JSONException {
		PhotoPathBean mainBean = new PhotoPathBean();
		PhotoPathBean pathBean = new PhotoPathBean();
		JSONObject mainJson = new JSONObject(jsonStr);
		JSONObject dataObject = mainJson.getJSONObject("data");
		// mainBean.result = mainJson.getString("result");
		// mainBean.message = mainJson.getString("message");
		pathBean.photo_path = dataObject.getString(photo_path);
//		mainBean.data = pathBean;
		return mainBean;
	}

	/**
	 * post 上传文件和参数（放进线程中跑 与handler结合）
	 */
	public void upload(String filePath, ArrayList<NameValuePair> params) {
		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";
		try {
			URL url = new URL(WKApplication.BASE_URL + "avatar_upload");
			L.wj("url : " + url.toString());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(5 * 1000); // 缓存的最长时间
			conn.setDoInput(true);// 允许输入
			conn.setDoOutput(true);// 允许输出
			conn.setUseCaches(false); // 不允许使用缓存
			System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
			conn.setRequestMethod("POST");
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Charsert", CHARSET);
			conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
					+ ";boundary=" + BOUNDARY);
			// 首先组拼文本类型的参数
			StringBuilder sb = new StringBuilder();
			int count = params.size();
			L.wj("params.count=" + count);
			for (int i = 0; i < count; i++) {
				NameValuePair entry = params.get(i);
				L.wj("name:" + entry.getName() + "  value:" + entry.getValue());
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINEND);
				sb.append("Content-Disposition: form-data; name=\""
						+ entry.getName() + "\"" + LINEND);
				sb.append("Content-Type: text/plain; charset=" + CHARSET
						+ LINEND);
				sb.append("Content-Transfer-Encoding: utf-8" + LINEND);
				sb.append(LINEND);
				sb.append(entry.getValue());
				sb.append(LINEND);
			}
			DataOutputStream outStream = new DataOutputStream(
					conn.getOutputStream());
			outStream.write(sb.toString().getBytes());
			// 发送文件数据
			if (TextUtils.isEmpty(filePath)) {
				return;
			}
			File file = new File(filePath);
			L.wj("file : " + file.toString());
			StringBuilder sb1 = new StringBuilder();
			sb1.append(PREFIX);
			sb1.append(BOUNDARY);
			sb1.append(LINEND);
			sb1.append("Content-Disposition: form-data; name=\"img\"; filename=\""
					+ file.getName() + "\"" + LINEND);
			sb1.append("Content-Type: application/octet-stream; charset="
					+ CHARSET + LINEND);
			sb1.append(LINEND);
			outStream.write(sb1.toString().getBytes());

			InputStream is = new FileInputStream(file);
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = is.read(bytes)) != -1) {
				outStream.write(bytes, 0, len);
			}
			is.close();
			outStream.write(LINEND.getBytes());
			// 请求结束标志
			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
			outStream.write(end_data);
			outStream.flush();
			outStream.close();
			// 得到响应码
			InputStream in = null;
			int res = conn.getResponseCode();
			if (res == 200) {
				in = conn.getInputStream();
				L.wj("result : " + dealResponseResult(in));
			} else {
				conn.disconnect();
				throw new IOException("服务器返回错误：" + res);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 处理输入流
	 */
	private String dealResponseResult(InputStream inputStream) {
		String resultData = null;
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		try {
			while ((len = inputStream.read(data)) != -1) {
				byteArrayOutputStream.write(data, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		resultData = new String(byteArrayOutputStream.toByteArray());
		return resultData;
	}

}
